<template>
  <div class="map-container">
    <div class="map-controls">
      <div class="control-group">
        <label>选择城市：</label>
        <select v-model="selectedCityId" @change="fetchData">
          <option v-for="city in cities" :value="city.id" :key="city.id">
            {{ city.name }}
          </option>
        </select>
      </div>
      
      <div class="control-group">
        <label>流向类型：</label>
        <div class="toggle-buttons">
          <button 
            @click="toggleFlowType('shipping')" 
            :class="{ active: showShipping }"
          >
            {{ showShipping ? '隐藏' : '显示' }}寄件流向
          </button>
          <button 
            @click="toggleFlowType('delivery')" 
            :class="{ active: showDelivery }"
          >
            {{ showDelivery ? '隐藏' : '显示' }}派件流向
          </button>
        </div>
      </div>
    </div>
    
    <div class="date-filter">
      <label>日期范围：</label>
      <input type="date" v-model="startDate" @change="fetchData">
      <span>至</span>
      <input type="date" v-model="endDate" @change="fetchData">
    </div>
    
    <div ref="chartRef" class="tech-map-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import chinaJson from '@/assets/china.json'

// 城市数据
const cities = ref([
  { id: 4, name: '深圳市', province: '广东省' },
  { id: 5, name: '珠海市', province: '广东省' },
  { id: 2, name: '广州市', province: '广东省' },
  { id: 6, name: '汕头市', province: '广东省' },
  { id: 7, name: '佛山市', province: '广东省' },
  // 可根据需要添加更多城市
])

// 响应式数据
const selectedCityId = ref(4) // 默认选择深圳市
const showShipping = ref(true)
const showDelivery = ref(true)
const startDate = ref('2025-07-01')
const endDate = ref('2025-07-31')
const shippingData = ref([])
const deliveryData = ref([])
const chartRef = ref(null)
let chartInstance = null
const currentCity = ref(null)

// 初始化
onMounted(() => {
  // 设置当前城市为默认选择
  currentCity.value = cities.value.find(city => city.id === selectedCityId.value)
  fetchData()
  initChart()
})

// 销毁实例
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', resizeChart)
})

// 切换流向类型显示状态
const toggleFlowType = (type) => {
  if (type === 'shipping') {
    showShipping.value = !showShipping.value
  } else if (type === 'delivery') {
    showDelivery.value = !showDelivery.value
  }
  updateChart()
}

// 获取省份中心点坐标
const getProvinceCoords = (provinceName) => {
  const provinceMap = {
    '北京市': [116.407526, 39.904030],
    '天津市': [117.201538, 39.085294],
    '河北省': [114.468664, 38.037057],
    '山西省': [112.562398, 37.873531],
    '内蒙古自治区': [111.765617, 40.817498],
    '辽宁省': [123.429440, 41.835441],
    '吉林省': [125.325990, 43.896536],
    '黑龙江省': [126.661669, 45.742347],
    '上海市': [121.473701, 31.230416],
    '江苏省': [118.763563, 32.061377],
    '浙江省': [120.153576, 30.287459],
    '安徽省': [117.283042, 31.861190],
    '福建省': [119.306239, 26.075302],
    '江西省': [115.858094, 28.682892],
    '山东省': [117.020359, 36.668530],
    '河南省': [113.753602, 34.765515],
    '湖北省': [114.342343, 30.545861],
    '湖南省': [112.983810, 28.112444],
    '广东省': [113.266530, 23.132191],
    '广西壮族自治区': [108.320004, 22.824020],
    '海南省': [110.349228, 20.017377],
    '重庆市': [106.504959, 29.533155],
    '四川省': [104.075931, 30.651651],
    '贵州省': [106.707410, 26.598194],
    '云南省': [102.710002, 25.046089],
    '西藏自治区': [91.117525, 29.647535],
    '陕西省': [108.954239, 34.265472],
    '甘肃省': [103.826308, 36.059421],
    '青海省': [101.780199, 36.620901],
    '宁夏回族自治区': [106.258754, 38.471317],
    '新疆维吾尔自治区': [87.627101, 43.793026],
    '香港特别行政区': [114.173355, 22.320048],
    '澳门特别行政区': [113.549130, 22.198750],
    '台湾省': [121.509062, 25.044332]
  };
  
  return provinceMap[provinceName] || [113.266530, 23.132191];
};

// 从后端获取数据
const fetchData = async () => {
  try {
    // 更新当前城市
    currentCity.value = cities.value.find(city => city.id === selectedCityId.value)
    
    // 获取寄件数据
    if (showShipping.value) {
      const shippingRes = await axios.get('http://localhost:8082/logistics/flows', {
        params: {
          cityId: selectedCityId.value,
          type: 0,
          startDate: startDate.value,
          endDate: endDate.value
        }
      })
      
      if (shippingRes.data.code === 200) {
        shippingData.value = shippingRes.data.data.map(item => ({
          from: currentCity.value.name,
          to: item.toName,
          value: item.value
        }))
      }
    }
    
    // 获取派件数据
    if (showDelivery.value) {
      const deliveryRes = await axios.get('http://localhost:8082/logistics/flows', {
        params: {
          cityId: selectedCityId.value,
          type: 1,
          startDate: startDate.value,
          endDate: endDate.value
        }
      })
      
      if (deliveryRes.data.code === 200) {
        deliveryData.value = deliveryRes.data.data.map(item => ({
          from: item.fromName,
          to: currentCity.value.name,
          value: item.value
        }))
      }
    }
    
    updateChart()
    
  } catch (error) {
    console.error('获取物流数据失败:', error)
  }
}

// 创建图表实例
const createChartInstance = () => {
  if (!chartRef.value) return null
  if (chartInstance) chartInstance.dispose()

  if (chartRef.value.clientWidth > 0 && chartRef.value.clientHeight > 0) {
    return echarts.init(chartRef.value, 'tech')
  }
  return null
}

// 初始化图表
const initChart = async () => {
  try {
    await nextTick()
    chartInstance = createChartInstance()
    
    if (!chartInstance) {
      setTimeout(initChart, 100)
      return
    }

    echarts.registerMap('china', chinaJson)
    updateChart()
    chartInstance.on('click', handleMapClick)
    window.addEventListener('resize', resizeChart)
    
  } catch (error) {
    console.error('地图初始化失败:', error)
  }
}

// 处理地图点击事件
const handleMapClick = (params) => {
  if (params.componentType === 'series' && params.seriesType === 'map') {
    console.log('点击省份:', params.name)
    chartInstance.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      name: params.name
    })
  }
}

// 更新图表
const updateChart = () => {
  if (!chartInstance || !currentCity.value) return
  chartInstance.setOption(getChartOption(), true)
}

// 响应屏幕大小变化
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 获取图表配置
const getChartOption = () => {
  // 准备流向线数据
  const shippingLines = shippingData.value.map(item => {
    const fromCoord = getProvinceCoords(currentCity.value.province)
    const toCoord = getProvinceCoords(item.to)
    return fromCoord && toCoord ? {
      fromName: item.from,
      toName: item.to,
      coords: [fromCoord, toCoord],
      value: item.value
    } : null
  }).filter(Boolean)

  const deliveryLines = deliveryData.value.map(item => {
    const fromCoord = getProvinceCoords(item.from)
    const toCoord = getProvinceCoords(currentCity.value.province)
    return fromCoord && toCoord ? {
      fromName: item.from,
      toName: item.to,
      coords: [fromCoord, toCoord],
      value: item.value
    } : null
  }).filter(Boolean)

  return {
    backgroundColor: 'transparent',
    title: {
      text: `${currentCity.value.name}物流流向可视化`,
      subtext: '寄件(绿色) | 派件(橙色)',
      left: 'center',
      textStyle: {
        color: '#00f2ff',
        fontSize: getResponsiveFontSize(24, 16),
        fontWeight: 'bold',
        textShadow: '0 0 10px rgba(0, 242, 255, 0.7)'
      },
      subtextStyle: {
        color: '#a0d1e5',
        fontSize: getResponsiveFontSize(16, 12),
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: params => {
        if (params.seriesType === 'map') {
          return `<div style="font-weight:bold; color: #00f2ff;">${params.name}</div>`
        } else if (params.seriesType === 'lines') {
          return `
            <div style="font-weight:bold; margin-bottom:5px; color: ${params.color};">${params.data.fromName} → ${params.data.toName}</div>
            <div>快递量: <b>${params.data.value}</b></div>
          `
        }
      },
      backgroundColor: 'rgba(0, 20, 50, 0.9)',
      borderColor: '#00f2ff',
      padding: 10,
      textStyle: {
        color: '#fff'
      }
    },
    visualMap: {
      min: 0,
      max: 60000,
      text: ['高', '低'],
      realtime: false,
      calculable: true,
      inRange: {
        color: ['#0a2dae', '#0b5bce', '#1990ff', '#38b1ff', '#50d2ff']
      },
      textStyle: {
        color: '#fff'
      },
      left: 'left',
      top: 'bottom'
    },
    geo: {
      map: 'china',
      roam: true,
      zoom: 1.8,
      center: [104.480689, 36.231046],
      label: {
        show: true,
        color: '#fff',
        fontSize: getResponsiveFontSize(10, 8)
      },
      itemStyle: {
        areaColor: '#0c2c5a',
        borderColor: '#00f2ff',
        borderWidth: 1,
        shadowColor: 'rgba(0, 242, 255, 0.3)',
        shadowBlur: 10
      },
      emphasis: {
        label: {
          color: '#fff',
          fontSize: getResponsiveFontSize(12, 10),
          fontWeight: 'bold'
        },
        itemStyle: {
          areaColor: '#1990ff',
          borderWidth: 2,
          shadowBlur: 15
        }
      },
      select: {
        label: {
          color: '#ff0',
          fontSize: getResponsiveFontSize(12, 10),
          fontWeight: 'bold'
        },
        itemStyle: {
          areaColor: '#ff0',
          borderColor: '#ff0'
        }
      }
    },
    series: [
      // 寄件流向
      {
        name: '寄件流向',
        type: 'lines',
        coordinateSystem: 'geo',
        zlevel: 2,
        
        effect: {
          show: true,
          period: 4,
          trailLength: 0.8,
          symbol: 'arrow',
          symbolSize: 10,
          color: '#00ff8c',
          
          opacity: showShipping.value ? 1 : 0,
        },
        lineStyle: {
          color: '#00ff8c',
          width: 0.1,
          opacity: showShipping.value ? 0.8 : 0,
          curveness: -0.5
        },
        data: shippingLines
      },
      // 派件流向
      {
        name: '派件流向',
        type: 'lines',
        coordinateSystem: 'geo',
        zlevel: 2,
        effect: {
          show: true,
          period: 4,
          trailLength: 0.9,
          symbol: 'arrow',
          symbolSize: 10,
          color: '#ff7d00',
          opacity: showDelivery.value ? 1 : 0,
        },
        lineStyle: {
          color: '#ff7d00',
          width: 0.1,
          opacity: showDelivery.value ? 0.8 : 0,
          curveness: -0.5
        },
        data: deliveryLines
      },
      // 当前城市标记
      {
        name: '当前城市',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        zlevel: 3,
        rippleEffect: {
          brushType: 'stroke',
          scale: 4
        },
        label: {
          show: true,
          position: 'right',
          formatter: currentCity.value.name,
          color: '#00f2ff',
          fontSize: 14
        },
        symbolSize: 15,
        itemStyle: {
          color: '#00ff8c'
        },
        data: [{
          name: currentCity.value.name,
          value: getProvinceCoords(currentCity.value.province)
        }]
      }
    ]
  }
}

// 响应屏幕变化
const getResponsiveFontSize = (largeSize, smallSize) => {
  return window.innerWidth < 768 ? smallSize : largeSize
}

// 注册科技感主题
echarts.registerTheme('tech', {
  backgroundColor: 'rgba(0, 10, 30, 0.8)',
  color: ['#00f2ff', '#1990ff', '#0b5bce', '#0a2dae'],
  title: {
    textStyle: {
      color: '#00f2ff'
    }
  },
  geo: {
    itemStyle: {
      borderColor: '#00f2ff'
    }
  }
})
</script>

<style scoped>
.map-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 15px;
  background: linear-gradient(135deg, #0c164f 0%, #1d1135 100%);
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 242, 255, 0.3);
}

.map-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(0, 20, 50, 0.7);
  border-radius: 6px;
}

.control-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.control-group label {
  color: #a0d1e5;
  font-size: 14px;
}

.control-group select {
  padding: 8px 12px;
  border: 1px solid #00f2ff;
  background: rgba(0, 30, 70, 0.7);
  color: #fff;
  border-radius: 4px;
  min-width: 150px;
  transition: all 0.3s;
}

.control-group select:focus {
  outline: none;
  border-color: #00ff8c;
  box-shadow: 0 0 10px rgba(0, 242, 255, 0.5);
}

.toggle-buttons {
  display: flex;
  gap: 10px;
}

.toggle-buttons button {
  padding: 8px 15px;
  border: 1px solid #00f2ff;
  background: rgba(0, 20, 50, 0.7);
  color: #a0d1e5;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 120px;
}

.toggle-buttons button:hover {
  background: rgba(0, 100, 180, 0.5);
  transform: translateY(-2px);
}

.toggle-buttons button.active {
  background: rgba(0, 242, 255, 0.3);
  color: #00f2ff;
  box-shadow: 0 0 10px rgba(0, 242, 255, 0.5);
  border-color: #00ff8c;
}

.date-filter {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  padding: 10px 15px;
  background: rgba(0, 20, 50, 0.7);
  border-radius: 6px;
}

.date-filter label {
  color: #a0d1e5;
  font-size: 14px;
}

.date-filter input {
  padding: 8px;
  border: 1px solid #00f2ff;
  background: rgba(0, 30, 70, 0.7);
  color: #fff;
  border-radius: 4px;
}

.date-filter span {
  color: #a0d1e5;
}

.tech-map-container {
  flex: 1;
  min-height: 500px;
  overflow: hidden !important;
  border-radius: 8px;
}

/* 移动设备优化 */
@media (max-width: 768px) {
  .map-controls {
    flex-direction: column;
    gap: 15px;
  }
  
  .control-group {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .toggle-buttons {
    flex-direction: column;
    width: 100%;
  }
  
  .toggle-buttons button {
    width: 100%;
  }
  
  .date-filter {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .date-filter input {
    width: 100%;
    box-sizing: border-box;
  }
  
  .tech-map-container {
    min-height: 300px;
  }
}
</style>